package com.cksys.achievement.config.login.qq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cksys.achievement.entity.Role;
import com.cksys.achievement.entity.User;
import com.cksys.achievement.entity.UserRole;
import com.cksys.achievement.enums.RegisterEnum;
import com.cksys.achievement.exception.MyUsernameNotFoundException;
import com.cksys.achievement.service.IRoleService;
import com.cksys.achievement.service.IUserRoleService;
import com.cksys.achievement.service.IUserService;
import com.cksys.achievement.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @ClassName: QQAuthenticationManager
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/4/16 14:29
 */
@Component
public class QQAuthenticationManager implements AuthenticationManager {

    @Autowired
    IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Collection<GrantedAuthority> authorities = new HashSet<>();
        String unionId = (String) authentication.getCredentials();
        User userByQqId = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getQqId, unionId));
        if (null == userByQqId) {
            return null;
        }
        if (!userByQqId.getRegister().equals(RegisterEnum.REGISTER_YES)) {
            throw new MyUsernameNotFoundException(CustomUserDetailsServiceImpl.NOT_AUDITED);
        }
        // 添加权限
        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", userByQqId.getId()));
        for (UserRole userRole : userRoles) {
            Role role = roleService.getById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName().getRoleName()));
        }
        org.springframework.security.core.userdetails.User principal = new org.springframework.security.core.userdetails.User(
                userByQqId.getUsername(), userByQqId.getPassword(), authorities);
        return new UsernamePasswordAuthenticationToken(principal, null, authorities);
    }


}
